package com.xm.xm.undercover

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Message
import android.util.Log
import com.google.gson.Gson
import com.xm.xm.undercover.bean.GetMessage
import kotlinx.android.synthetic.main.activity_test.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class TestActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        bt_sendMes.setOnClickListener {
            SendRequestWithOkHttp()
//            connect()

        }
    }

    private fun connect(){
        val url = URL("https://www.baidu.com")
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        connection.connectTimeout = 8000
        connection.readTimeout = 8000
        val input = connection.inputStream
        connection.disconnect()

    }

    /**
     * "http://192.168.10.11:8080/test/get"
     */
    private fun SendRequestWithOkHttp(){
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://192.168.10.11:8080/test/get")
                    .build()
                val response = client.newCall(request).execute()
                Log.d("testActivity"," get mess")
                val responseData = response.body()?.string()
                if (responseData!=null){
                    parseJSONWithJSONObject(responseData)
                }
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    private fun parseJSONWithJSONObject(jsonData: String) {
        try {
            val gson = Gson()
            val message = gson.fromJson<GetMessage>(jsonData,GetMessage::class.java)
            test_mes.text = message.mes
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
}
